<?php

header('Content-type: application/json');

if (isset($_REQUEST['id']) and is_numeric($_REQUEST['id'])) {
	$categories = $db->fetchAll("SELECT * FROM shop_categories WHERE site_id=? AND parent_id=? ORDER BY sort", array($site['id'], $_REQUEST['id']));
	foreach($categories as &$category) { $category['product_count'] = $db->fetchOne("SELECT COUNT(*) FROM shop_products p JOIN shop_categories_products cp ON p.id=cp.product_id AND category_id=? AND deleted=0", $category['id']); }
	for($i=0;$i<count($categories);$i++) {
		$categories[$i]['children'] = $db->fetchOne("SELECT COUNT(*) FROM shop_categories WHERE parent_id=?", $categories[$i]['id']);
	}
	$json = array();
	foreach ($categories as &$category) {
		$class = '';
		if ($category['children'] == 0) $class .= ' no-children';
		$json[] = array(
			'attributes' => array(
				'id'        => $category['id'],
				'class'     => $class, 
				'rel'       => ($category['parent_id']==0 ? 'root' : 'category'), 
				'parent_id' => $category['parent_id']
			),
			'state' => 'closed',
			'data' => array('title' => "<span style='background:none;padding:0'>{$category['title']}</span> ({$category['product_count']})", 'icon' => "/admin/backend/resources/images/icons/folder.png")
		);
	}
	
	echo json_encode($json);
	
}

